package com.canvas.base;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * web页面全局处理
 * @Author: 宗恣
 * @Date: 2018/8/31 0031 10:45
 */
@Controller
@Slf4j
public class AppErrorController implements ErrorController {

    private static final String ERROR_PAH = "/error";

    private ErrorAttributes errorAttributes;

    @Override
    public String getErrorPath() {
        return ERROR_PAH;
    }

    @Autowired
    public AppErrorController(ErrorAttributes errorAttributes) {
        this.errorAttributes = errorAttributes;
    }

    /**
     * web页面错误处理
     */
    @RequestMapping(value = ERROR_PAH, produces = "text/html")
    public String errorPageHandler(HttpServletRequest request, HttpServletResponse response) {
        int status = response.getStatus();

        switch (status) {
            case 403:
                return "403";
            case 404:
                return "404";
            case 500:
                return "500";
        }

        return "index";
    }

    /**
     * 除web页面外的错误处理, 比如Json/XML等
     */
    @RequestMapping(value = ERROR_PAH)
    @ResponseBody
    public ApiResponse errorApiHandler(HttpServletRequest request) {
//        ServletRequestAttributes requestAttributes = new ServletRequestAttributes(request);

        MyWebRequest myWebRequest = new MyWebRequest(request);

        Map<String, Object> attributes = this.errorAttributes.getErrorAttributes( myWebRequest, false);

        int status = getStaus(request);

        return ApiResponse.ofMessage(status, String.valueOf(attributes.getOrDefault("message", "error")));
    }

    private int getStaus(HttpServletRequest request) {
        Integer status = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (null != status) {
            return status;
        }
        return 500;
    }

}
